// src/component/ProductADForm.tsx
import React, {useContext, useState} from 'react';
import {
    Form,
    Input,
    Button,
    Space,
    message,
    Upload
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { fileService } from '../api/service/FileService';
import ProductADContext from "../context/ProductADContext.tsx";
import type {ProductAd} from "../api/service/ProductADService.tsx";

// 定义表单值类型
interface FormValues {
    productId: number;
}

interface ProductADFormProps {
    ad: ProductAd | null; // 添加这一行
    onCancel: () => void;
    loading?: boolean;
    onSuccess?: () => void;
}

const ProductADForm: React.FC<ProductADFormProps> = ({ onCancel, loading, onSuccess }) => {
    const [form] = Form.useForm();
    const [coverFileList, setCoverFileList] = useState<UploadFile[]>([]);
    const productADContext = useContext(ProductADContext);

    if (!productADContext) {
        throw new Error('ProductADContext is not available');
    }

    const { createAd } = productADContext;

    // 处理表单提交
    const onFinish = async (values: FormValues) => {
        try {
            const { productId } = values; // 从表单值中获取productId

            // 如果有上传的文件，则先上传文件
            if (coverFileList.length > 0 && coverFileList[0].originFileObj) {
                // 上传文件并获取文件key
                const fileKey = await fileService.uploadFile(coverFileList[0].originFileObj, "product-ad");

                // 调用createAd方法，传入正确的参数
                const result = await createAd({
                    productId: productId.toString(),
                    coverAddr: fileKey // 使用coverAddr字段而不是fileKey
                });

                if (result) {
                    message.success('广告创建成功');
                    form.resetFields();
                    setCoverFileList([]);
                    onSuccess?.(); // 调用成功回调
                } else {
                    message.error('广告创建失败');
                }
            } else {
                message.warning('请上传封面图片');
                return;
            }
        } catch (uploadError) {
            console.error('文件上传失败:', uploadError);
            message.error('文件上传失败: ' + (uploadError instanceof Error ? uploadError.message : '未知错误'));
            return;
        }
    };

    return (
        <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
        >
            <Form.Item
                name="productId"
                label="商品ID"
                rules={[{ required: true, message: '请输入商品ID' }]}
            >
                <Input type="number" placeholder="请输入商品ID" />
            </Form.Item>

            <Form.Item
                name="coverImage"
                label="封面图片"
            >
                <Upload
                    listType="picture"
                    maxCount={1}
                    fileList={coverFileList}
                    onChange={({ fileList }) => setCoverFileList(fileList)}
                    beforeUpload={() => false} // 阻止自动上传
                >
                    <Button icon={<UploadOutlined />}>上传图片</Button>
                </Upload>
            </Form.Item>

            <Form.Item>
                <Space>
                    <Button type="primary" htmlType="submit" loading={loading}>
                        创建
                    </Button>
                    <Button onClick={() => {
                        form.resetFields();
                        setCoverFileList([]);
                        onCancel();
                    }}>
                        取消
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    );
};

export default ProductADForm;
